
/**
 * 点击屏蔽组件
 * @see TouchBlocker.ts
 */

import * as cc from "cc";
import NodeUtils from "../../../../../framework/utils/NodeUtils";

const { ccclass, menu, property } = cc._decorator;
@ccclass
@menu('Guide/TouchBlocker')
export default class TouchBlocker extends cc.Component {

    // @property({ type: cc.Node, tooltip: CC_DEV && '可点击的节点' })
    public target: cc.Node = null;

    private isBlockAll: boolean = false;

    private isPassAll: boolean = false;

    /**是否透传点击 */
    private isPassClick : boolean = false;

    /**点击回调事件 */
    private _onClick: () => void = null;
    protected onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
    }

    protected onDestroy() {
        this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this);
    }

    /**
     * touchstart 回调
     * @param event 事件
     */
    private onTouchStart(event: cc.EventTouch) {
        if (this.isPassAll) {
            event.preventSwallow = true;
            return;
        }
        if (this.isBlockAll || !this.target) {
            event.propagationImmediateStopped = true;
            return;
        }
    
        let targetRect = NodeUtils.getWorldRect(this.target);
        let isContains = targetRect.contains(event.getUILocation());
        if (!isContains) {
            event.propagationImmediateStopped = true ;
        } else{
            if (this._onClick) {
                this._onClick();
                this._onClick = null;
            }
            if (!this.isPassClick) {
                event.propagationImmediateStopped = true;
            }
            event.preventSwallow = true;
        }
    }

    /**
     * 屏蔽所有点击
     */
    public blockAll() {
        this.isBlockAll = true;
        this.isPassAll = false;
    }

    /**
     * 放行所有点击
     */
    public passAll() {
        this.isPassAll = true;
        this.isBlockAll = false;
    }

    /**
     * 设置可点击的节点
     * @param node 
     * @param onClick
     * @param isPassClick 是否透传点击事件
     */
    public setTarget(node: cc.Node, isPassClick: boolean, onClick: () => void) {
        this.target = node;
        this.isBlockAll = false;
        this.isPassAll = false;
        this._onClick = onClick;
        this.isPassClick = isPassClick;
    }

}
